package com.jinxin.platform.cdinfogo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jinxin.platform.cdinfogo.pojo.domain.CdinfogoDevice;
import com.jinxin.platform.cdinfogo.mapper.CdinfogoDeviceMapper;
import com.jinxin.platform.cdinfogo.pojo.form.DeviceForm;
import com.jinxin.platform.cdinfogo.pojo.vo.DeviceContVo;
import com.jinxin.platform.cdinfogo.pojo.vo.SysUserVO;
import com.jinxin.platform.cdinfogo.rpc.CdInfoGoRpcService;
import com.jinxin.platform.cdinfogo.service.CdinfogoDeviceService;
import com.jinxin.platform.cdinfogo.utils.URLEncoder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.jinxin.platform.base.common.pojo.JsonResult;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (CdinfogoDevice)表服务实现类
 *
 * @author zhangpeng
 * @since 2021-06-28 17:23:37
 */
@Service("cdinfogoDeviceService")
public class CdinfogoDeviceServiceImpl implements CdinfogoDeviceService {
    @Resource
    private CdinfogoDeviceMapper cdinfogoDeviceMapper;
    @Resource
    private CdInfoGoRpcService cdInfoGoRpcService;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JsonResult queryById(String id) {
        CdinfogoDevice cdinfogoDevice = this.cdinfogoDeviceMapper.queryById(id);
        return JsonResult.ok(cdinfogoDevice);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param cdinfogoDevice 实例对象
     * @return 对象列表
     */
    @Override
    public JsonResult queryAll(CdinfogoDevice cdinfogoDevice) {
        List<CdinfogoDevice> cdinfogoDeviceList =  this.cdinfogoDeviceMapper.queryAll(cdinfogoDevice);
        return JsonResult.ok(cdinfogoDeviceList);
    }

    /**
     * 新增数据
     *
     * @param cdinfogoDevice 实例对象
     * @return 实例对象
     */
    @Override
    public JsonResult insert(CdinfogoDevice cdinfogoDevice) {
        int i = this.cdinfogoDeviceMapper.insert(cdinfogoDevice);
        return i > 0 ? JsonResult.ok("新增成功",cdinfogoDevice) : JsonResult.error("新增失败！");
    }

    /**
     * 修改数据
     *
     * @param cdinfogoDevice 实例对象
     * @return 实例对象
     */
    @Override
    public JsonResult update(CdinfogoDevice cdinfogoDevice) {
        int i = this.cdinfogoDeviceMapper.update(cdinfogoDevice);
        return i > 0 ? JsonResult.ok("修改成功！",null) : JsonResult.error("修改失败！");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public JsonResult deleteById(String id) {
        return this.cdinfogoDeviceMapper.deleteById(id) > 0 ? JsonResult.ok("删除成功！",null) : JsonResult.error("删除失败！");
    }

    @Override
    public JsonResult pageList(DeviceForm deviceForm) {
        PageHelper.startPage(deviceForm.getPage(),deviceForm.getLimit());
        CdinfogoDevice build = CdinfogoDevice.builder().deviceMac(deviceForm.getDeviceMac()).deviceName(deviceForm.getDeviceName()).deviceType(deviceForm.getDeviceType()).build();
        List<CdinfogoDevice> cdinfogoDevices = cdinfogoDeviceMapper.queryAll(build);
        PageInfo<CdinfogoDevice> cdinfogoDevicePageInfo = new PageInfo<>(cdinfogoDevices);
        return JsonResult.ok(cdinfogoDevicePageInfo);
    }

    @Override
    public JsonResult updateDevice() {
        SysUserVO currentUser = cdInfoGoRpcService.getCurrentUser();
        List<CdinfogoDevice> deviceList = cdInfoGoRpcService.getDevice();
        if (deviceList != null && deviceList.size() > 0){
            deviceList.forEach(d -> {
                CdinfogoDevice device = cdinfogoDeviceMapper.queryByMac(d.getDeviceMac());
                if(device != null){
                    device.setDeviceName(d.getDeviceName());
                    device.setNickName(d.getNickName());
                    device.setAccount(d.getAccount());
                    cdinfogoDeviceMapper.update(device);
                }else {
                    d.setCreateTime(LocalDateTime.now());
                    d.setCreator(currentUser.getUserName());
                    cdinfogoDeviceMapper.insert(d);
                }
            });
        }

        return JsonResult.ok("同步成功"+ (deviceList != null ? deviceList.size() : 0) +"条",null);
    }

    @Override
    public JsonResult queryCentByDeviceId(String deviceId) {
        List<DeviceContVo> deviceContVos = cdinfogoDeviceMapper.queryCentByDeviceId(deviceId);
        List<DeviceContVo> kqList = new ArrayList<>();
        List<DeviceContVo> countList = new ArrayList<>();
        JSONObject jsonObject = new JSONObject();
        deviceContVos.forEach( d -> {
            if(d.getShowType().equals("1")){
                jsonObject.put("weather",d);
            }else if(d.getShowType().equals("2")){
                kqList.add(d);
            }else {
                countList.add(d);
            }
        });
        jsonObject.put("kqList",kqList);
        jsonObject.put("countList",countList);
        return JsonResult.ok(jsonObject);
    }

    @Override
    public JsonResult controllerDevice(String ids) {
        List<String> strings = JSON.parseArray(ids, String.class);
        strings.forEach( id -> {
            CdinfogoDevice cdinfogoDevice = cdinfogoDeviceMapper.queryById(id);
            List<DeviceContVo> deviceContVos = cdinfogoDeviceMapper.queryCentByDeviceId(id);
            deviceContVos.forEach( cent -> {
                try{
                    if("2".equals(cent.getShowType())){
                        Integer items = cdInfoGoRpcService.getItems(cent.getContent());
                        String p2 = (cent.getShowFont() == null ? "" : cent.getShowFont())
                                + (cent.getShowColor() == null ? "" : cent.getShowColor())
                                + (cent.getContent() == null ? "" : cent.getContent()) + "　" + items;
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("p1",cent.getShowArea());
                        jsonObject.put("p2",p2);
                        String s = jsonObject.toJSONString();
                        String s1 = URLEncoder.encodeURI(s);
                        cdInfoGoRpcService.controlDevice(cdinfogoDevice,s1,"Distribution content");
                    }else {
                        String p2 = (cent.getShowFont() == null ? "" : cent.getShowFont())
                                + (cent.getShowColor() == null ? "" : cent.getShowColor())
                                + (cent.getContent() == null ? "" : cent.getContent());
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("p1",cent.getShowArea());
                        jsonObject.put("p2",p2);
                        String s = jsonObject.toJSONString();
                        String s1 = URLEncoder.encodeURI(s);
                        cdInfoGoRpcService.controlDevice(cdinfogoDevice,s1,"Distribution content");
                    }
                }catch (Exception e){
                    System.out.println(e.toString());
                }


            });
        });

        return JsonResult.ok();
    }
}